package com.fish.admin.module.system.manager;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fish.admin.module.system.domain.dto.SysRolePageQueryDTO;
import com.fish.admin.module.system.domain.entity.SysRole;
import com.fish.admin.module.system.mapper.SysRoleMapper;
import com.fish.common.core.context.UserContextManager;
import com.fish.common.core.enums.EnabledEnum;
import com.fish.common.mybatisplus.query.MPJLambdaWrapperX;
import com.fish.common.mybatisplus.util.PageUtils;
import com.fish.common.support.util.EnumUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class SysRoleManager {

    private final SysRoleMapper sysRoleMapper;

    public SysRole getById(Long roleId, EnabledEnum enabledEnum) {
        return sysRoleMapper.selectOne(SysRole::getId, roleId, SysRole::getEnabled, enabledEnum.getValue());
    }

    public IPage<SysRole> page(SysRolePageQueryDTO pageQuery) {

        MPJLambdaWrapperX<SysRole> queryWrapper = new MPJLambdaWrapperX<>();
        if (UserContextManager.getRequiredContext().isAdmin()){
            queryWrapper.isNull(SysRole::getTenantId);
        }else{
            queryWrapper.eq(SysRole::getCreatorId, UserContextManager.getRequiredContext().getUserId());
        }
        queryWrapper.likeIfPresent(SysRole::getName, pageQuery.getName())
                .orderByAsc(SysRole::getSort);
        return sysRoleMapper.selectPage(PageUtils.build(pageQuery), queryWrapper);

    }

    public void save(SysRole sysRole) {
        sysRoleMapper.insert(sysRole);
    }

    public SysRole getById(Long id) {
       return sysRoleMapper.selectById(id);
    }

    public void deleteById(Long id) {
        sysRoleMapper.deleteById(id);
    }

    public void updateById(SysRole sysRole) {
        sysRoleMapper.updateById(sysRole);
    }

    public List<SysRole> list(EnabledEnum enabled) {
        MPJLambdaWrapperX<SysRole> queryWrapper = new MPJLambdaWrapperX<>();
        queryWrapper.eq(SysRole::getEnabled, EnumUtils.getValue(enabled));
        if (UserContextManager.getRequiredContext().isAdmin()){
            queryWrapper.isNull(SysRole::getTenantId);
        }else{
            queryWrapper.eq(SysRole::getCreatorId, UserContextManager.getRequiredContext().getUserId());
        }
        return sysRoleMapper.selectList(queryWrapper);
    }
}
